var express = require('express');
var app = express();
var fs = require("fs");
var unzip = require("unzip2");
const path  = require('path')



var bodyParser = require('body-parser');
var multer  = require('multer');
const staticPath = path.resolve(__dirname, '../static')
console.log(staticPath)
app.use(express.static(staticPath));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/tmp/'}).array('image'));
app.get('/upload.html', function (req, res) {
   res.sendFile( __dirname + "/" + "upload.html" );
})
app.use((req, res, next) => {
  console.log(req)
  next();
})

app.post('/file_upload', function (req, res) {
   var des_file = __dirname + "/static/" + req.files[0].originalname;
   fs.readFile( req.files[0].path, function (err, data) {
        fs.writeFile(des_file, data, function (err) {
         if( err ){
              console.log( err );
         }else{
               response = {
                   message:'File uploaded successfully', 
                   filename:req.files[0].originalname
              };
          }
          console.log( response );
          res.end( function(){
            fs.createReadStream(__dirname+'/static/'+response.filename).pipe(unzip.Extract({ path: __dirname+'/static' }));
          } );
       });
   });
})

var server = app.listen(8081, function () {

  var host = server.address().address
  var port = server.address().port

  console.log("应用实例，访问地址为 http://%s:%s", host, port)

})